<template>
	<div>
		<div :id="domName"></div>
		<el-dialog
			:title="$t('common.components.tip')"
			:visible.sync="isImgEdIor"
			width="90%"
			:before-close="handleClose"
		>
			<div slot="title" class="imge-header-title">
				<div class="leftText">
					{{ $t('common.components.edit_picure') }}
				</div>
				<div class="rightText">
					<el-button @click="isImgEdIor = false">
						{{ $t('common.cancel') }}
					</el-button>
					<el-button type="primary" @click="handleClose">
						{{ $t('common.confirm') }}
					</el-button>
				</div>
			</div>
			<div class="drawing-container">
				<div :id="`${domName}e`"></div>
			</div>
			<!-- <span slot="footer" class="dialog-footer">
				<el-button @click="isImgEdIor = false">取 消</el-button>
				<el-button type="primary" @click="handleClose">
					确 定
				</el-button>
			</span> -->
		</el-dialog>
	</div>
</template>

<script>
import E from 'wangeditor'
import i18next from 'i18next'
import 'tui-image-editor/dist/tui-image-editor.css'
import 'tui-color-picker/dist/tui-color-picker.css'
import ImageEditor from 'tui-image-editor'
import { customLang } from './util'

let insertImgFn1
export default {
	model: {
		prop: 'value',
		event: 'change'
	},
	props: {
		value: {
			type: String,
			default: ''
		},
		meanArray: {
			// 自定义菜单
			type: Array,
			default: null
		},
		domName: {
			type: String,
			require: true,
			default: ''
		},
		editVisible: {
			type: Boolean,
			default: () => false
		},
		containerBgColor: {
			type: String,
			default: '#fff'
		}
	},

	data() {
		return {
			instance: null,
			isImgEdIor: false,
			firstImg: false,
			img: '',
			img1: '',
			// 默认有这么多菜单，meanArray有值以meanArray为准
			defaultMeanus: [
				'head',
				'bold',
				'fontSize',
				'fontName',
				'italic',
				'underline',
				'strikeThrough',
				'foreColor',
				'emoticon',
				'backColor',
				'justify',
				'image'
			],
			editor: ''
		}
	},
	watch: {
		editVisible: {
			handler(val) {
				this.$nextTick(() => {
					setTimeout(() => {
						if (!val) this.editor.disable()
						else this.editor.enable()
					}, 500)
				})
			},
			deep: true,
			immediate: true
		},
		value: function(value) {
			if (value !== this.editor.txt.html()) {
				this.editor.txt.html(this.value)
			}
		}
		// value为编辑框输入的内容，这里我监听了一下值，当父组件调用得时候，如果给value赋值了，子组件将会显示父组件赋给的值
	},
	mounted() {
		const that = this
		that.$nextTick(function() {
			that.init()

			that.setHtml(this.value)
		})
	},
	methods: {
		handleClose() {
			this.isImgEdIor = false
			const base64String = this.instance.toDataURL() // base64 文件
			const data = window.atob(base64String.split(',')[1])
			const ia = new Uint8Array(data.length)
			for (let i = 0; i < data.length; i++) {
				ia[i] = data.charCodeAt(i)
			}
			const blob = new Blob([ia], { type: 'image/png' }) // blob 文件
			// this.img = URL.createObjectURL(blob)
			// this.firstImg = !this.firstImg
			insertImgFn1(URL.createObjectURL(blob))
			this.instance = null
			// const form = new FormData()
			// form.append('image', blob)
			// upload file
		},

		init() {
			const _this = this
			this.editor = new E(`#${this.domName}`)
			this.editor.config.colors = [
				'#000000',
				'#b0b0b0',
				'#ffffff',
				'#FAF0E6',
				'#F0F8FF',
				'#4682B4',
				'#00FFFF',
				'#32CD32',
				'#CD5C5C',
				'#D2B48C',
				'#D8BFD8',
				'#8B8378',
				'#CFCFCF',
				'#B4CDCD',
				'#EEC900',
				'#6E8B3D'
			]
			this.editor.config.height = 400
			this.editor.config.uploadImgShowBase64 = true // 使用 base64 保存图片
			this.editor.config.showLinkImg = false
			const map = {
				zh_CN: 'zh-CN',
				en_US: 'en',
				vi_VN: 'vi',
				th_TH: 'th'
			}

			// 选择语言
			this.editor.config.lang = map[this.$i18n.locale]
			// 自定义语言
			this.editor.config.languages[map[this.$i18n.locale]] = customLang
			this.editor.i18next = i18next
			this.editor.config.customUploadImg = function(
				resultFiles,
				insertImgFn
			) {
				// resultFiles 是 input 中选中的文件列表
				// insertImgFn 是获取图片 url 后，插入到编辑器的方法
				const formData = new FormData()
				formData.append('file', resultFiles[0])
				_this.$api.agentImageUploadAPI(formData).then((res) => {
					if (res.code === 200) {
						const img = res.data
						_this.img = img
						insertImgFn1 = insertImgFn
						// 上传图片，返回结果，将图片插入到编辑器中
						insertImgFn(_this.img)
					} else {
						_this.$message.error(_this.$t('common.fail_upload'))
					}
				})
			}
			this.setMenus() // 设置菜单
			this.editor.config.onchange = (html) => {
				_this.$emit('change', html) // 将内容同步到父组件中
			}
			this.editor.config.menuFixed = false
			this.editor.create() // 创建编辑器
			this.editor.$textContainerElem.elems[0].style.backgroundColor = this.containerBgColor
		},
		imgInit() {
			this.instance = new ImageEditor(
				document.querySelector(`#${this.domName}e`),
				{
					includeUI: {
						loadImage: {
							path: this.img,
							name: 'image'
						},
						menu: [
							'resize',
							'crop',
							'rotate',
							'draw',
							'shape',
							'icon',
							'text',
							'filter'
						], // 底部菜单按钮列表 隐藏镜像flip和遮罩mask
						initMenu: 'draw', // 默认打开的菜单项
						menuBarPosition: 'bottom' // 菜单所在的位置
						// locale: locale_zh, // 本地化语言为中文
						// theme: customTheme // 自定义样式
					},
					cssMaxWidth: 800, // canvas 最大宽度
					cssMaxHeight: 600 // canvas 最大高度
				}
			)
			// document.getElementsByClassName('tui-image-editor-main')[0].style.top =
			// 	'45px' // 图片距顶部工具栏的距离
			// document.getElementsByClassName(
			// 	'tie-btn-reset tui-image-editor-item help'
			// )[0].style.display = 'none' // 隐藏顶部重置按钮
		},

		setMenus() {
			// 设置菜单
			if (this.meanArray) {
				this.editor.config.menus = this.meanArray
			} else {
				this.editor.config.menus = this.defaultMeanus
			}
		},
		getHtml() {
			// 得到文本内容
			return this.editor.txt.html()
		},
		setHtml(txt) {
			// 设置富文本里面的值
			this.editor.txt.html(txt)
		}
	}
}
</script>
<style lang="scss" scoped>
::v-deep .el-dialog__header {
	padding: 0;
	.imge-header-title {
		line-height: 60px;
		padding: 0 20px;
		display: flex;
		justify-content: space-between;
		border-bottom: 1px solid #ccc;
		.leftText {
			font-weight: 700;
		}
		.rightText {
			font-size: 14px;
		}
	}
}
::v-deep .w-e-toolbar {
	z-index: 1 !important;
}
::v-deep .w-e-text-container {
	z-index: 0 !important;
}
.drawing-container {
	height: 700px;
}
</style>
